import axios, { AxiosRequestConfig } from 'axios';
import { message, Modal } from 'ant-design-vue';
import { getAuthorization } from '@/utils/auth'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { createVNode } from 'vue';
import router from '@/router'
// 创建请求路由
const request = axios.create({
    baseURL: (window as any).config.api,
    timeout: (window as any).config.timeout,
})

// 请求头拦截器
request.interceptors.request.use(
    (config: any) => {
        if (config.method === 'get' || config.method === 'GET') {
            config.url = (config?.url?.indexOf('?') === -1) ? config.url + '?_=' + (new Date()).getTime() : config.url + '&_=' + (new Date()).getTime()
        }
        if (getAuthorization()) {
            config.headers[(window as any).config.authorization] = getAuthorization() // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        return config
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
)

// 返回值拦截器
request.interceptors.response.use(
    (response) => {
        const status = response.status
        let data
        if (status == 200) {
            data = response.data
            const code = data.code
            if (code == 0) { // 正常
                return data.data
            } else if (code == -1) { // 已知异常
                let error = data.error
                message.error(error);
                return Promise.reject('error')
            } else if (code == 300) { // 未知异常
                message.destroy()
                let error = data.error
                message.error(error);
                return Promise.reject('error')
            } else if (code == 500) { // 令牌异常
                let error = data.error
                Modal.destroyAll()
                Modal.confirm({
                    title: '警告',
                    icon: createVNode(ExclamationCircleOutlined),
                    content: `${error}`,
                    okText: '重新登陆',
                    cancelText: '关闭',
                    onOk() {
                        router.push({ name: "login" })
                    }
                });
                return Promise.reject('error')
            }
        }
        return data;
    },
    (error) => {
        message.destroy()
        if (error.toString().indexOf("Error: Network") !== -1) {
            message.warning("网络错误,检查您的网络是否正常!")
            return Promise.reject(error)
        } else if (error.toString().indexOf('Error: timeout') !== -1) {
            message.warning("请求超时,检查您的网络是否正常!")
            return Promise.reject(error)
        }
        // 对请求错误做些什么
        return Promise.reject(error);
    }
)

export default request;
